function generateQuestions() {
    const form = document.getElementById('questionForm');
    const progressDiv = document.getElementById('progress');
    const resultDiv = document.getElementById('result');
    
    // 显示加载状态和进度信息
    progressDiv.innerHTML = `
        <div class="text-center mb-3">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2" id="progressText">正在生成题目...</p>
            <p class="text-muted" id="speedText"></p>
        </div>
        <div class="progress">
            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
        </div>
    `;
    progressDiv.style.display = 'block';
    resultDiv.innerHTML = '';

    // 获取选中的题型和对应数量
    const questionTypes = [];
    const types = [
        { id: 'choiceQuestion', numId: 'choiceQuestionNum' },
        { id: 'calculationQuestion', numId: 'calculationQuestionNum' },
        { id: 'shortAnswerQuestion', numId: 'shortAnswerQuestionNum' },
        { id: 'fillInBlankQuestion', numId: 'fillInBlankQuestionNum' }
    ];

    types.forEach(type => {
        const checkbox = document.getElementById(type.id);
        const numInput = document.getElementById(type.numId);
        if (checkbox.checked && numInput.value > 0) {
            questionTypes.push({
                type: checkbox.value,
                count: parseInt(numInput.value)
            });
        }
    });

    if (questionTypes.length === 0) {
        alert('请至少选择一种题型并设置数量');
        return;
    }

    fetch('/generate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            course_name: document.getElementById('courseName').value,
            question_types: questionTypes,
            knowledge_content: document.getElementById('knowledgeContent').value
        })
    })
    .then(response => {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        function processChunk({ done, value }) {
            if (done) {
                return buffer;
            }

            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop();

            lines.forEach(line => {
                if (line.startsWith('data: ')) {
                    try {
                        const data = JSON.parse(line.slice(6));
                        if (data.progress) {
                            document.querySelector('.progress-bar').style.width = `${data.progress}%`;
                            document.getElementById('progressText').textContent = `正在生成题目... ${data.progress}%`;
                        }
                        if (data.speed) {
                            document.getElementById('speedText').textContent = `生成速度: ${data.speed} tokens/s`;
                        }
                        if(data.questions) {
                            // 隐藏进度条
                            progressDiv.style.display = 'none';
                            displayResults(data); 
                        }
                    } catch (e) {}
                }
            });

            return reader.read().then(processChunk);
        }

        return reader.read().then(processChunk);
    })
    .then(response => {

    })
    .then(data => {
        // 隐藏进度条
        progressDiv.style.display = 'none';
        console.log(data);
       
    })
    .catch(error => {
        console.error('请求失败:', error);
        progressDiv.style.display = 'none';
        resultDiv.innerHTML = `<div class="alert alert-danger">请求失败: ${error.message}</div>`;
    });
}

function displayResults(data) {
    const resultDiv = document.getElementById('result');
    
    if (data.raw_response) {
        resultDiv.innerHTML = `<pre class="bg-white p-3 rounded">${data.raw_response}</pre>`;
    } else {
        let html = '<div class="questions-container">';
        data.questions.forEach(question => {
            html += `
                <div class="card mb-3">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <span class="me-2">题目 ${question.id}</span>
                            <span class="badge bg-secondary">${question.type}</span>
                        </div>
                        <span class="badge bg-primary">难度: ${question.difficulty}/5</span>
                    </div>
                    <div class="card-body">
                        <div class="question-content mb-3">
                            <h5 class="card-title">${question.content}</h5>
                            ${question.options ? `
                                <div class="options-list mt-3">
                                    ${question.options.map((opt, idx) => `
                                        <div class="form-check mb-2">
                                            <input class="form-check-input" type="radio" name="question${question.id}" id="q${question.id}opt${idx}" disabled>
                                            <label class="form-check-label" for="q${question.id}opt${idx}">
                                                ${['A','B','C','D'][idx]}. ${opt}
                                            </label>
                                        </div>
                                    `).join('')}
                                </div>
                            ` : ''}
                            ${question.formula ? `
                                <div class="formula mt-3 p-2 bg-light rounded">
                                    <strong>公式：</strong>
                                    <code class="ms-2">${question.formula}</code>
                                </div>
                            ` : ''}
                            ${question.diagram ? `
                                <div class="diagram mt-3 p-2 bg-light rounded">
                                    <strong>图示：</strong>
                                    <div class="diagram-content mt-2">${question.diagram}</div>
                                </div>
                            ` : ''}
                            ${question.blanks ? `
                                <div class="blanks mt-3">
                                    <div class="blank-list">
                                        ${question.blanks.map((blank, idx) => `
                                            <div class="blank-item mb-2">
                                                <strong>空${idx + 1}：</strong>
                                                <input type="text" class="form-control" placeholder="请填写答案" disabled>
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            ` : ''}
                        </div>
                        <div class="answer-section p-3 bg-light rounded">
                            <div class="answer mb-2">
                                <strong>答案：</strong> ${question.answer}
                            </div>
                            <div class="explanation">
                                <strong>解释：</strong> ${question.explanation}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
        resultDiv.innerHTML = html;
    }
}

// 添加表单提交事件监听
document.addEventListener('DOMContentLoaded', () => {
    const types = [
        { id: 'choiceQuestion', numId: 'choiceQuestionNum' },
        { id: 'calculationQuestion', numId: 'calculationQuestionNum' },
        { id: 'shortAnswerQuestion', numId: 'shortAnswerQuestionNum' },
        { id: 'fillInBlankQuestion', numId: 'fillInBlankQuestionNum' }
    ];

    types.forEach(type => {
        const checkbox = document.getElementById(type.id);
        const numInput = document.getElementById(type.numId);

        checkbox.addEventListener('change', () => {
            numInput.disabled = !checkbox.checked;
            if (!checkbox.checked) {
                numInput.value = 0;
            }
        });

        // 初始化禁用状态
        numInput.disabled = !checkbox.checked;
    });

    // 添加表单提交事件处理
    document.getElementById('questionForm').addEventListener('submit', (e) => {
        e.preventDefault(); // 阻止表单默认提交行为
        generateQuestions(); // 执行生成题目函数
    });
});